<template>
    <div id="map">
        <!--<remote-js></remote-js>-->
        <div id="top" v-if="isShowTips">
            <div id="Tips"></div>
            <!-- time和distance -->
            <div id="timesAdistance"></div>
            <!-- 转向牌 -->
            <div id="turnTips">
                <img src="/img/tips/ZHI.png" id="turnTipsZHI" v-if="isShowStraight" alt="">
                <img src="/img/tips/ZUO.png" id="turnTipsZUO" v-if="isShowLeft" alt="">
                <img src="/img/tips/YOU.png" id="turnTipsYOU" v-if="isShowRight" alt="">
            </div>
            <!--退出导航-->
            <div class="quit-navi" @click="imitateDel">
                <i class="el-icon-close"></i>
            </div>
        </div>

        <div class="controldiv" v-if="isShowControlPanel">
            <div @click="">
                <el-switch
                        v-model="isopenOrClose"
                        active-color="#13ce66"
                        @change="switchChange"
                >
                </el-switch>
            </div>
            <div @click="showRoutePanel"><img src="../assets/navi-icon.png"/></div>
            <div @click="showDrawPanel"><img src="../assets/report_grey.png"/></div>
            <div @click="cleanMap"><i class="el-icon-delete" style="font-size: 25px;"></i></div>
            <div @click="zoomToSelfLocation"><img src="../assets/img/locate_checked.png"/></div>
            <div @click="findAllGaofenUpdate"><i :class="['el-icon-view', isGFShow && 'highlight']" style="font-size: 25px;"></i></div>
            <!--<div @click="initDrawCtrl"> </div>-->
            <!--<div></div>-->
        </div>

        <div class="routePanel" v-if="isShowRoutePanel">
            <h3 style="display: inline">任务</h3>
            <i class="el-icon-close" style="float: right;font-size: 16px;" @click="closeRoutePanel"></i>
            <el-form :label-position="'left'" label-width="50px" size="mini">
                <el-form-item label="名称">
                    <el-input v-model="routeForm.name" placeholder="请输入名称"></el-input>
                </el-form-item>

                <el-form-item label="起点">
                    <el-input v-model="startPointStr" placeholder="请选择起点">
                        <el-button slot="append" icon="el-icon-coordinate" @click.prevent="getStartPoint"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="终点">
                    <el-input v-model="endPointStr" placeholder="请选择终点">
                        <el-button slot="append" icon="el-icon-coordinate" @click="getEndPoint"></el-button>
                    </el-input>
                </el-form-item>

                <el-form-item label="其他">
                    <el-collapse accordion>
                        <el-collapse-item style="min-width: 30px;" title="其他配置">
                            <el-form-item label="坡度">
                                <el-input v-model="routeForm.altitude"></el-input>
                            </el-form-item>
                            <el-form-item label="过水">
                                <el-radio-group v-model="routeForm.resource">
                                    <el-radio label="城市规划"></el-radio>
                                    <el-radio label="野外规划"></el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="过水">
                                <el-radio-group v-model="routeForm.resourceWater">
                                    <el-radio label="不过水"></el-radio>
                                    <el-radio label="过水"></el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="森林">
                                <el-radio-group v-model="routeForm.resourceForest">
                                    <el-radio label="不过森林"></el-radio>
                                    <el-radio label="过森林"></el-radio>
                                </el-radio-group>
                            </el-form-item>

                        </el-collapse-item>
                    </el-collapse>

                </el-form-item>

                <el-form-item class="item-btn">
                    <el-button type="info" @click.stop="routeAnalyze">路径规划</el-button>
                    <el-button type="primary" @click.stop="imitateNavigation2">开始导航</el-button>
                </el-form-item>
            </el-form>

        </div>

        <div class="drawPanel" v-if="isShowDrawPanel">
            <h3 style="display: inline">绘制</h3>
            <i class="el-icon-close" style="float: right;font-size: 16px;" @click="closeDrawPanel"></i>
            <div class="draw_box">
                <el-form ref="drawForm" :model="drawForm" label-width="80px" size="mini">

                    <el-form-item label="名称">
                        <el-input v-model="drawForm.layerName"></el-input>
                    </el-form-item>

                    <el-form-item label="图层">
                        <el-cascader
                                v-model="selLayerName"
                                :options="drawForm.options"
                                @change="handleChange"
                                style="width: 100%;"></el-cascader>
                    </el-form-item>
                    <el-form-item label="标识" prop="flag">
                        <el-radio-group v-model="drawForm.flag">
                            <el-radio label="敌方"></el-radio>
                            <el-radio label="我方"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item class="item-btn">
                        <el-button type="info"  @click="closeDrawPanel">取消操作</el-button>
                        <el-button type="primary" @click="postNewLayer">创建图层</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>


        <!-- 实s时位置 -->
        <!--<div id="me"-->
        <!--style="position: absolute;bottom:30px;left:10px;z-index: 99999;width: 80px;min-height: 10px;background: #000;color:#fff">-->
        <!--</div>-->
        <!--<div id="barControl">-->
        <!--<img src="" v-if="isNorthDirection"/>-->
        <!--<img src="" v-if="!isNorthDirection"/>-->
        <!--<p v-if="isNorthDirection">北朝向</p>-->
        <!--<p v-if="!isNorthDirection">道路朝向</p>-->
        <!--</div>-->

    </div>

</template>

<script>
    // import '../../public/js/iife-fun.js'
    import axios from 'axios'; // 引入axios
    import mapboxgl from "mapbox-gl";
    import "mapbox-gl/dist/mapbox-gl.css";
    // import '../../public/js/leaflet/leaflet-mapbox-gl.js'
    // import 'leaflet/dist/leaflet.css'
    // import * as L from 'leaflet'
    import $ from 'jquery'
    import {mapState, mapGetters, mapActions, mapMutations} from 'vuex';
    // import {addGaofenItem, addNewTask, sendMessage} from '@/request/api.js'
    import {addMapService} from '@/utils/map/maptool'

    export default {
        name: "Map",
        data() {
            return {
                // src3:require('../../public/js/remotejs'),
                roadNetHost: "http://192.168.0.121:3000",
                map: this.$rootMap.map,
                isopenOrClose: true,
                layerIds: [],
                sourceArr: [],
                markerArr: [],
                pathNode: [],
                tujingPointArr: [],
                boxSourceIds: [],
                boxLayerIds: [],
                pointsLayer: null,
                linesLayer: null,
                layergroup: null,
                zoom: 3,
                isShowRoutePanel: false,
                isShowNavConPanel: false,
                isShowTips: false,
                isShowStraight: false,
                isShowLeft: false,
                isShowRight: false,
                isNorthDirection: true,
                isRoadDirection: false,
                startPoint: null,
                wayPoint: null,
                barrierPoint: null,
                endPoint: null,
                imitatePointList: [],
                imitateGuides: [],
                imitateRoutes: [],
                imitatePoint: null,//移动的marker
                imitateTime: null,//计时器
                lastLine: null,
                isGFShow: false,//高分数据是否在地图上显示

                isShowControlPanel: true,
                startPointStr: "",
                endPointStr: '',
                isShowDrawPanel: false,
                routeForm: {
                    isUsingRoad: 1,
                    name: '',
                    resource: 1,
                    altitude: '',
                    resourceWater: '',
                    resourceForest: '',
                    equHigh: null, //装备高度 仅在路网路径规划时 结合道路限高使用
                    equWeigh: null, // double装备重量，路网规划时候，结合道路限重使用
                    equWidth: null,// double 装备宽度，路网路径规划时，结合道路限宽使用
                    modes: [
                        {name: '距离最短', i: 'el-icon-discover'},
                        {name: '时间最短', i: 'el-icon-pie-chart'},
                        // {name: '装备类型', i: 'el-icon-set-up'}
                    ],
                    slopeValue: null,
                    modesNoRoad: [
                        {name: '坡度', i: 'el-icon-finished'},
                        {name: '不过水', i: 'el-icon-ice-cream', active: false, equType: 0},
                        {name: '不过森林', i: 'el-icon-grape', active: false, equLx: 0},
                    ],
                    mode: 0,
                    maxSlopDegree: null,
                    pdCollection: null,
                    syCollection: null,
                    slCollection: null,
                },
                selLayerName: [],
                selLayerTypeNum: 1,//1点2线3面
                drawForm: {
                    layerName: '',
                    drawType: '点',
                    options: [{
                        value: '点图层',
                        label: '点图层',
                        children: [{
                            value: '卫星地面站',
                            label: '卫星地面站'
                        }, {
                            value: '通信塔',
                            label: '通信塔'
                        }, {
                            value: '防空雷达',
                            label: '防空雷达'
                        }, {
                            value: '瞭望塔',
                            label: '瞭望塔'
                        }, {
                            value: '地面定位增强站',
                            label: '地面定位增强站'
                        }, {
                            value: '其他点',
                            label: '其他点'
                        }]
                    },
                        {
                            value: '线图层',
                            label: '线图层',
                            children: [{
                                value: '临时修筑道路',
                                label: '临时修筑道路'
                            }, {
                                value: '禁行通信路段',
                                label: '禁行通信路段'
                            }, {
                                value: '屏障建筑工事',
                                label: '屏障建筑工事'
                            }, {
                                value: '战壕防御工事',
                                label: '战壕防御工事'
                            }, {
                                value: '其它线',
                                label: '其它线'
                            }]
                        },
                        {
                            value: '面图层',
                            label: '面图层',
                            children: [{
                                value: '雷区',
                                label: '雷区'
                            }, {
                                value: '管控区',
                                label: '管控区'
                            }, {
                                value: '侦察区',
                                label: '侦察区'
                            }, {
                                value: '信号干扰区',
                                label: '信号干扰区'
                            }, {
                                value: '地质灾害区',
                                label: '地质灾害区'
                            }, {
                                value: '其它面',
                                label: '其它面'
                            }]
                        }],
                    flag: "我方",//0敌方1我方
                },
                coordsStr: '',
                taskPointArr: [],
                taskPointStr: ''
            }
        },
        created() {
            // console.log(this.$roadObj);
            //任务跳转过来
            if (this.$globalObj.points.length != 0) {
                let tmpPointArr = this.$globalObj.points
                let tmpTaskdesc = this.$globalObj.taskDesc;
                this.routeForm.name = tmpTaskdesc;
                this.startPointStr = tmpPointArr[0].longitude + ',' + tmpPointArr[0].latitude;
                let lastIndex = tmpPointArr.length - 1;
                this.endPointStr = tmpPointArr[lastIndex].longitude + ',' + tmpPointArr[lastIndex].latitude;
                let tmpNode = tmpPointArr.map((item, index) => {
                    let tempnode = {}
                    tempnode.latitude = item.latitude
                    tempnode.longitude = item.longitude
                    this.pathNode.push(tempnode)
                });
            }
            //高分数
            if (this.$globalObj.geojson) {

            }
        },
        beforeDestroy() {
            this.cleanMap()
            this.map.remove()
        },
        mounted() {
            // this.addDataToMap();
            // console.log(this.$route);
            this.initMap();
            if (this.$globalObj.points.length != 0) {
                this.addLine(this.pathNode);
                this.isShowRoutePanel = true;
            }
            if (this.$globalObj.geojson) {
                this.cleanMap();
                if (this.map.loaded()) {

                } else {
                    this.map.on('load', () => {
                        // console.log(this.$globalObj.geojson)
                        this.clearMap(this.markerArr, this.layerIds, this.sourceArr);
                        let geoJson = JSON.parse(this.$globalObj.geojson);
                        this.map.addSource('lineSource', {
                            'type': 'geojson',
                            'data': geoJson
                        });
                        this.sourceArr.push('lineSource')
                        this.map.addLayer({
                            id: 'route1',
                            type: 'line',
                            source: 'lineSource',
                            layout: {},
                            paint: {
                                'line-color': '#31881e',
                                'line-width': 2
                            }
                        });
                        this.layerIds.push('route1');
                    });
                }
            }

        },
        methods: {
            initMap() {
                let location = $App.getSelfLocation()
                this.map = new mapboxgl.Map({
                    container: 'map',
                    center: (location && location.lat) ? new mapboxgl.LngLat(location.lon,location.lat) : new mapboxgl.LngLat(118.79619, 31.86705),
                    // style: "http://192.168.0.121:5095/bdgis/mapstyle/basic-style.json",
                    // style: "http://192.168.0.120:8088/styles/basic/style.json",
                    // style: "http://192.168.0.120:8088/styles/night/style.json",
                    style: "http://192.168.0.121:5095/bdgis/mapstyle/basic-style.json",
                    zoom: 16,
                    antialias: false,
                });
                let nav = new mapboxgl.NavigationControl();
                this.map.addControl(nav, 'bottom-right');
                let scale = new mapboxgl.ScaleControl({
                    maxWidth: 80,
                    unit: 'imperial'
                });
                this.map.addControl(scale);
                scale.setUnit('metric');
                this.map.loadImage(
                    'static/img/icon.png',
                    (error, image) => {
                        this.map.addImage('icon', image)
                    })

                //const marker = new mapboxgl.Marker().setLngLat([location.lon,location.lat]).addTo(this.map)
            },
            zoomToSelfLocation() {
                let location = $App.getSelfLocation() && JSON.parse($App.getSelfLocation())
                this.map.panTo([location.lon,location.lat],{duration: 1000})
            },
            findAllGaofenUpdate() {
                if (this.isGFShow) {
                    this.removeGFMapData()
                } else {
                    let res = JSON.parse($App.findAllGaofenUpdate())
                    console.log(res)
                    let pointFeatures = [], lineFeatures = [], polygonFeatures = []
                    res.forEach((obj, i) => {
                        if(obj.wz) {
                            let wzArr = obj.wz.split(',')
                            let locationArr = []
                            for (let i = 0; i < wzArr.length; i = i + 2) {
                                locationArr.push([wzArr[i], wzArr[i + 1]])
                            }
                            if(obj.lx == 1) {
                                pointFeatures.push({
                                    type: 'Feature',
                                    properties: {
                                        description: `<strong>${obj.smname}</strong>`,
                                        icon: 'icon'
                                    },
                                    geometry: {
                                        type: 'Point',
                                        coordinates: [locationArr[0][0],locationArr[0][1]]
                                    }
                                })
                            } else if (obj.lx == 2) {
                                lineFeatures.push({
                                    type: 'Feature',
                                    geometry: {
                                        type: 'LineString',
                                        coordinates: locationArr
                                    }
                                })
                            } else {
                                polygonFeatures.push({
                                    type: 'Feature',
                                    geometry: {
                                        type: 'Polygon',
                                        coordinates: [[...locationArr, locationArr[0]]]
                                    }
                                })
                            }
                        }
                    })
                    this.removeGFMapData()

                    //添加点数据源
                    this.map.addSource('gfPointSource', {
                        type: 'geojson',
                        data: {
                            type: 'FeatureCollection',
                            features: pointFeatures
                        }
                    })
                    this.sourceArr.push('gfPointSource')
                    this.map.addLayer({
                        'id': 'gfPointLayer',
                        'type': 'symbol',
                        'source': 'gfPointSource',
                        'layout': {
                            'icon-image': ['get', 'icon'],
                            'icon-allow-overlap': true
                        }
                    })
                    this.layerIds.push('gfPointLayer')
                    this.map.on('click', 'gfPointLayer', (e) => {
                        const coordinates = e.features[0].geometry.coordinates.slice()
                        const description = e.features[0].properties.description

                        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                            coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360
                        }

                        new mapboxgl.Popup()
                            .setLngLat(coordinates)
                            .setHTML(description)
                            .addTo(this.map)
                    })

                    //添加线数据源
                    lineFeatures.forEach((lineData, i) => {
                        this.map.addSource('gfLineSource' + i, {
                            type: 'geojson',
                            data: lineData
                        })
                        this.sourceArr.push('gfLineSource' + i)
                        this.map.addLayer({
                            id: 'gfLineLayer' + i,
                            type: 'line',
                            source: 'gfLineSource' + i,
                            layout: {},
                            paint: {
                                'line-color': '#409eff',
                                'line-width': 8
                            }
                        })
                        this.layerIds.push('gfLineLayer' + i)
                    })

                    //添加面数据源
                    polygonFeatures.forEach((polygonData, i) => {
                        this.map.addSource('gfPolygonSource' + i, {
                            type: 'geojson',
                            data: polygonData
                        })
                        this.sourceArr.push('gfPolygonSource' + i)
                        this.map.addLayer({
                            id: 'gfPolygonLayer' + i,
                            type: 'fill',
                            source: 'gfPolygonSource' + i,
                            'paint': {
                                'fill-color': '#0080ff',
                                'fill-opacity': 0.2
                            }
                        })
                        this.map.addLayer({
                            'id': 'outline' + i,
                            'type': 'line',
                            'source': 'gfPolygonSource' + i,
                            'paint': {
                                'line-color': '#888',
                                'line-width': 3
                            }
                        })
                        this.layerIds.push('gfPolygonLayer' + i,'outline' + i)
                    })
                }
                this.isGFShow = !this.isGFShow
            },
            removeGFMapData(point = true, line = true, polygon = true) {
                if(point) {
                    if (this.layerIds.indexOf('gfPointLayer') >= 0) {
                        this.map.removeLayer('gfPointLayer')
                        this.$delete(this.layerIds, this.layerIds.indexOf('gfPointLayer'))
                        this.map.removeSource('gfPointSource')
                        this.$delete(this.sourceArr, this.sourceArr.indexOf('gfPointSource'))
                    }
                }
                if(line) {
                    this.layerIds.forEach((layerId, i) => {
                        if (layerId.indexOf('gfLineLayer') >= 0) {
                            this.map.removeLayer(layerId)
                            this.$delete(this.layerIds, i)
                        }
                    })
                    this.sourceArr.forEach((source, i) => {
                        if (source.indexOf('gfLineSource') >= 0) {
                            this.map.removeSource(source)
                            this.$delete(this.sourceArr, i)
                        }
                    })
                }
                if(polygon) {
                    this.layerIds.forEach((layerId, i) => {
                        if (layerId.indexOf('gfPolygonLayer') >= 0) {
                            this.map.removeLayer(layerId)
                            this.$delete(this.layerIds, i)
                        }
                    })
                    this.layerIds.forEach((layerId, i) => {
                        if (layerId.indexOf('outline') >= 0) {
                            this.map.removeLayer(layerId)
                            this.$delete(this.layerIds, i)
                        }
                    })
                    this.sourceArr.forEach((source, i) => {
                        if (source.indexOf('gfPolygonSource') >= 0) {
                            this.map.removeSource(source)
                            this.$delete(this.sourceArr, i)
                        }
                    })

                }
            },
            imitateNavigation2() {
                this.isShowControlPanel = false;
                this.isShowRoutePanel = false;
                let imitatePointList = this.imitatePointList;
                let imitateGuides = this.imitateGuides;

                let i = 0;//标识模拟点
                let guide = {}
                let j = 0;//标识guides
                let msg

                clearInterval(this.imitateTime);
                //添加起始点marker
                this.imitatePoint = new mapboxgl.Marker().setLngLat(new mapboxgl.LngLat(imitatePointList[i].longitude, imitatePointList[i].latitude)).addTo(this.map);
                this.markerArr.push(this.imitatePoint)

                //设置地图倾斜
                this.map.jumpTo({
                    pitch: 60
                });
                this.TTSFunction('从起始点出发');

                // 展示导航信息
                // this.isShowTips = true;
                // this.isShowRoutePanel = false;
                // this.isShowNavConPanel = true;
                // let a = this.formatSecToDate((imitatePointList.length - i) * 2000 / 1000);
                // let b = imitatePointList[imitatePointList.length - 1].m - imitatePointList[i].m;//剩余距离
                // $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米');

                switch (guide.turnType) {
                    case '开始':
                        $("#Tips").html(guide.describe + '后' + guide.turnType);
                        this.isShowStraight = true;
                        this.isShowRight = false;
                        this.isShowLeft = false;
                        setTimeout(function () {
                            this.isShowStraight = false;
                        }, 4000)
                        break;
                    case '直行':
                        this.isShowStraight = true;
                        this.isShowRight = false;
                        this.isShowLeft = false;
                        setTimeout(function () {
                            this.isShowStraight = false;
                        }, 4000)
                        break;
                    case '左转':
                        this.isShowStraight = false;
                        this.isShowRight = false;
                        this.isShowLeft = true;
                        setTimeout(function () {
                            this.isShowLeft = false;
                        }, 4000)
                        break;
                    case '右转':
                        this.isShowStraight = false;
                        this.isShowRight = true;
                        this.isShowLeft = false;
                        setTimeout(function () {
                            this.isShowRight = false;
                        }, 4000)
                        break;
                }
                // if (guide.turnType) {
                //     msg = new window.SpeechSynthesisUtterance(guide.describe + '后' + guide.turnType);
                //     window.speechSynthesis.speak(msg);
                // }
                // i++;
                j++;
                guide = imitateGuides[j]
                this.map.jumpTo({
                    bearing: guide.degrees
                })
                console.log('J=' + j);
                this.imitateTime = setInterval(() => {
                    if (this.imitatePoint) {
                        this.imitatePoint.remove();
                    }
                    let longitude = imitatePointList[i].longitude;
                    let latitude = imitatePointList[i].latitude;
                    let tmpLngLat = new mapboxgl.LngLat(longitude, latitude);
                    this.imitatePoint = new mapboxgl.Marker().setLngLat(tmpLngLat).addTo(this.map);
                    this.map.panTo(tmpLngLat);

                    this.isShowTips = true;
                    this.isShowRoutePanel = false;
                    this.isShowNavConPanel = true;
                    let a = this.formatSecToDate((imitatePointList.length - i) * 2000 / 1000)
                    let b = this.imitatePointList[imitatePointList.length - 1].m - imitatePointList[i].m;
                    $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米')
                    console.log("guide:" + guide.m)
                    console.log("car:" + imitatePointList[i].m)
                    if (j < imitateGuides.length && imitatePointList[i].m > guide.m) {
                        j++
                        guide = imitateGuides[j]
                        if (guide.degrees) {
                            this.map.jumpTo({
                                bearing: guide.degrees
                            })
                        }
                        console.log('J=' + j);
                        switch (guide.turnType) {
                            case '直行':
                                // this.map.mapboxLayer._jumpToMap(0, 30)
                                this.isShowStraight = true;
                                this.isShowRight = false;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    this.isShowStraight = false;
                                }, 4000)
                                break;
                            case '左转':
                                // this.map.mapboxLayer._jumpToMap(0, 60)
                                this.isShowStraight = false;
                                this.isShowRight = false;
                                this.isShowLeft = true;
                                setTimeout(function () {
                                    this.isShowLeft = false;
                                }, 4000)
                                break;
                            case '右转':
                                // this.map.mapboxLayer._jumpToMap(0, 90)
                                this.isShowStraight = false;
                                this.isShowRight = true;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    this.isShowRight = false;
                                }, 4000)
                                break;
                        }
                        if (guide.turnType) {
                            $("#Tips").html(guide.describe + '后' + guide.turnType)
                            // msg = new window.SpeechSynthesisUtterance(guide.describe + '后' + guide.turnType);
                            // window.speechSynthesis.speak(msg);
                            this.TTSFunction(guide.describe + '后' + guide.turnType);
                        }
                        // j++
                        if (j >= imitateGuides.length) {
                            // j = 0;
                            this.isShowTips = true;
                            this.isShowRoutePanel = false;
                            this.isShowNavConPanel = false;
                        }
                    }
                    console.log(i);
                    i++
                    if (i >= imitatePointList.length) {
                        clearInterval(this.imitateTime);
                        let that = this;
                        this.isShowStraight = false;
                        this.isShowRight = false;
                        this.isShowLeft = false;
                        clearInterval(this.imitateTime)
                        // this.imitatePoint.remove();
                        that.imitateDel()
                        // msg = new window.SpeechSynthesisUtterance("导航结束");
                        // window.speechSynthesis.speak(msg);
                        this.TTSFunction("导航结束")
                        this.isShowControlPanel = true;
                    }
                }, 3000)
            },
            // 退出模拟导航
            imitateDel() {
                clearInterval(this.imitateTime);
                this.isShowControlPanel = true;
                this.isShowTips = false;
                this.map.jumpTo({
                    bearing: 0,
                    pitch: 0
                })
                $("#Tips").html('')
                $("#timesAdistance").html('')
            },
            // 暂停模拟导航
            imitateStop() {
                clearInterval(this.imitateTime)
            },
            // 继续模拟导航
            imitateGo() {
                console.log(i, j)
                this.imitateTime = setInterval(() => {
                    if (this.imitatePoint) {
                        this.map.removeLayer(this.imitatePoint)
                    }
                    this.imitatePoint = L.marker([this.imitatePointList[i].latitude, this.imitatePointList[i].longitude]).addTo(this.map);

                    let a = this.formatSecToDate((this.imitatePointList.length - i) * 2000 / 1000)
                    let b = this.imitatePointList[this.imitatePointList.length - 1].m - this.imitatePointList[i].m
                    $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米')
                    // 展示导航信息
                    if (this.imitatePointList[i].m >= guide.m) {
                        if (guide.turnType) {
                            $("#Tips").html(guide.describe + '后' + guide.turnType)
                        }
                        switch (guide.turnType) {
                            case '直行':
                                this.isShowStraight = true;
                                this.isShowRight = false;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    $("#turnTipsZHI").hide()
                                }, 4000)
                                break;
                            case '左转':
                                this.isShowStraight = false;
                                this.isShowRight = true;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    $("#turnTipsZUO").hide()
                                }, 4000)
                                break;
                            case '右转':
                                this.isShowStraight = false;
                                this.isShowRight = false;
                                this.isShowLeft = true;
                                setTimeout(function () {
                                    $("#turnTipsYOU").hide()
                                }, 4000)
                                break;
                        }
                        if (guide.turnType) {
                            // msg = new SpeechSynthesisUtterance(guide.describe + '后' + guide.turnType);
                            // window.speechSynthesis.speak(msg);
                        }
                        j = j + 1
                        guide = imitateGuides[j]
                        if (j >= imitateGuides.length - 1) {
                            j = 0
                            setTimeout(function () {
                                $("#Tips").html('')
                                $("#timesAdistance").html('')
                            }, 4000)
                        }
                    }
                    i = i + 1
                    if (i >= this.imitatePointList.length) {
                        clearInterval(this.imitateTime)
                        this.map.removeLayer(this.imitatePoint)
                        setTimeout(function () {
                            // msg = new SpeechSynthesisUtterance(this.imitateGuides[this.imitateGuides.length - 1].describe);
                            // window.speechSynthesis.speak(msg);
                            this.imitateDel()
                        }, 5000)
                    }
                }, 2000)
            },
            formatTooltip(val) {
                return val / 100;
            },
            //秒转时分秒
            formatSecToDate(sec) {
                if (!sec) {
                    return '-'
                }
                var min = Math.floor(sec % 3600);//分钟
                return Math.floor(sec / 3600) + "时" + Math.floor(min / 60) + "分" + sec % 60 + "秒";
            },
            chulishuju(data) {
                let featureArray = [];
                for (let i in data) {
                    let feature = {
                        type: data[i].type,
                        geomety: {
                            type: data[i].geometry.type,
                            coordinates: data[i].geometry.coordinates
                        }
                    }
                    featureArray.push(feature);
                }
                return featureArray;
            },
            getStartPoint() {
                let _self = this;
                _self.clickEvent && this.map.off('click', _self.clickEvent);

                function startClick(e) {
                    _self.startPointStr = e.lngLat.lat.toFixed(6) + "," + e.lngLat.lng.toFixed(6);
                    if (_self.startPoint) {
                        _self.startPoint.remove();
                    }
                    let dom = document.createElement('img');
                    dom.className = 'marker';
                    dom.style.backgroundImage = `url(./img/start.png)`;
                    _self.startPoint = new mapboxgl.Marker({
                        element: dom,
                        offset: [0, -10]
                    }).setLngLat(new mapboxgl.LngLat(e.lngLat.lng, e.lngLat.lat)).addTo(_self.map);
                    _self.markerArr.push(_self.startPoint);//添加起点marker到数组
                }

                _self.clickEvent = startClick;
                _self.map.on('click', _self.clickEvent);
            },
            getEndPoint() {
                let _self = this;
                _self.clickEvent && this.map.off('click', _self.clickEvent);

                function endClick(e) {
                    _self.endPointStr = e.lngLat.lat.toFixed(6) + "," + e.lngLat.lng.toFixed(6);
                    if (_self.endPoint) {
                        _self.endPoint.remove();
                    }
                    let dom = document.createElement('img');
                    dom.className = 'marker';
                    dom.style.backgroundImage = `url(./img/end.png)`;
                    _self.endPoint = new mapboxgl.Marker({
                        element: dom,
                        offset: [0, -10]
                    }).setLngLat(new mapboxgl.LngLat(e.lngLat.lng, e.lngLat.lat)).addTo(_self.map);
                    _self.markerArr.push(_self.endPoint);//添加终点marker到数组
                }

                _self.clickEvent = endClick;
                _self.map.on('click', _self.clickEvent);

            },
            async routeAnalyze() {
                this.clickEvent && this.map.off('click', this.clickEvent);
                // debugger
                if (!this.startPoint) {
                    this.$message({
                        message: '请选择起点',
                        type: 'warning'
                    });
                    return;
                }
                if (!this.endPoint) {
                    this.$message({
                        message: '请选择终点',
                        type: 'warning'
                    });
                    return;
                }
                // 箭头-右
                var svgXML =
                    `<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M529.6128 512L239.9232 222.4128 384.7168 77.5168 819.2 512 384.7168 946.4832 239.9232 801.5872z" p-id="9085" fill="#ffffff"></path>
            </svg>
            `
                let that = this;
                //给图片对象写入base64编码的svg流
                var svgBase64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXML)));
                let arrowIcon = new Image(20, 20)
                arrowIcon.src = svgBase64
                arrowIcon.onload = function () {
                    that.map.addImage('arrowIcon', arrowIcon)
                }
                //获取导航相关数据
                let featureObj = await this.getNavmes();
                console.log('geojson数据为：');
                console.log(JSON.stringify(featureObj));

                if (!featureObj.pointFeature) {
                    this.$message({
                        message: '路径规划失败',
                        type: 'danger'
                    });
                    return
                }
                //跳转到起点
                let firstLng = this.imitatePointList[0].longitude;
                let firstLat = this.imitatePointList[0].latitude;
                let firstLngLat = new mapboxgl.LngLat(firstLng, firstLat);
                this.map.panTo(firstLngLat);

                let lineFeature = featureObj.lineFeature;
                let pointFeature = featureObj.pointFeature;
                //添加线图层
                this.map.addSource('lineSource', {
                    'type': 'geojson',
                    'data': lineFeature
                });
                this.map.addLayer({
                    id: 'route1',
                    type: 'line',
                    source: 'lineSource',
                    layout: {},
                    paint: {
                        'line-color': '#31881e',
                        'line-width': 8
                    }
                });
                this.layerIds.push("route1");
                //添加箭头图层
                this.map.loadImage('/static/ZHI.png', (error, image) => {
                    if (error) throw error
                    this.map.addSource('arrowSource', {
                        type: 'geojson',
                        data: pointFeature
                    });
                    this.map.addLayer({
                        id: 'arrowLayer',
                        type: 'symbol',
                        source: 'lineSource',
                        layout: {
                            'symbol-placement': 'line',
                            'symbol-spacing': 100,
                            'icon-image': 'arrowIcon',
                            'icon-size': 0.5
                        }
                    });

                });
                this.layerIds.push("arrowLayer");

                //新增任务，返回xh
                this.postNewTask();

            },
            async getNavmes() {
                let navMesObj = {
                    lineFeature: null,
                    pointFeature: null
                }
                let data = {
                    "isUsingRoad": 1,
                    "isReturnGuide": 1,
                    "nodes": [{"latitude": this.startPoint._lngLat.lat, "longitude": this.startPoint._lngLat.lng}, {
                        "latitude": this.endPoint._lngLat.lat,
                        "longitude": this.endPoint._lngLat.lng
                    }]
                };
                // let res = await axios.post('http://192.168.0.121:5080/bdgis/route', data);
                let res = $App.routeAnalyze(JSON.stringify(data));
                let result = JSON.parse(res);
                console.log("路径规划信息："+res);

                // console.log(result)

                if (result.data != null) {
                    this.imitateGuides = result.data.guides;
                    this.imitatePointList = result.data.points;
                    // console.log(this.imitateGuides);
                    // console.log(this.imitatePointList);
                    let points = result.data.points;
                    let feature = {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            type: 'LineString',
                            coordinates: []//coordinates
                        }
                    };
                    let pointsSourceData = {
                        type: 'FeatureCollection',
                        features: []
                    }
                    for (let i = 0; i < points.length; i++) {
                        let pointFeature = {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: []//coordinates
                            }
                        };
                        let tmpLat = points[i].latitude;
                        let tmpLon = points[i].longitude;
                        let tmpPoint = [tmpLon, tmpLat];
                        //线的geojson
                        feature.geometry.coordinates.push(tmpPoint);
                        //多个点的geojson
                        if (i > 1) {
                            pointFeature.geometry.coordinates = tmpPoint;
                            pointsSourceData.features.push(pointFeature);
                        }
                    }
                    navMesObj.lineFeature = feature;
                    navMesObj.pointFeature = pointsSourceData;

                    this.$store.commit('SETSTARTPOINT', this.startPoint);
                    this.$store.commit('SETENDPOINT', this.endPoint);
                    this.$store.commit('SETPOINTS', points);
                    this.$store.commit('SETGUIDES', result.data.guides);
                    this.$store.commit('SETLINEFEATURE', feature);
                    this.$store.commit('SETPOINTFEATURE', pointsSourceData);
                }
                return navMesObj;

            },
            closeRoutePanel() {
                this.isShowRoutePanel = false;
                this.cleanMap();
            },
            closeDrawPanel() {
                this.isShowDrawPanel = false;
            },
            handleChange(value) {
                console.log(value);
                // console.log(this.selLayerName);
                //初始化绘图控件
                let geoTypeStr = this.selLayerName[0];
                console.log(geoTypeStr)
                if (geoTypeStr == '点图层') {
                    this.selLayerTypeNum = 1;
                    this.initPointTool();
                    this.$message({
                        message: '请点击地图，绘制点'
                    });
                } else if (geoTypeStr == '线图层') {
                    this.selLayerTypeNum = 2;
                    this.initLineTool();
                    this.$message({
                        message: '请点击地图，绘制线'
                    });
                } else {
                    this.selLayerTypeNum = 3;
                    this.initPoygonTool();
                    this.$message({
                        message: '请点击地图,绘制面'
                    });
                }
            },
            initPointTool() {
                this.map.getCanvas().style.cursor = 'crosshair';
                // clearLayerAndSource();
                this.clearMap(this.markerArr, this.layerIds, this.sourceArr);
                let isDraw = true;
                this.map.doubleClickZoom.disable();//禁止双击缩放
                let jsonPoint = {
                    'type': 'FeatureCollection',
                    'features': []
                };
                let source = this.map.getSource('points');
                if (source) {
                    this.map.getSource(points).setData(jsonPoint);
                } else {
                    this.map.addSource('points', {
                        type: 'geojson',
                        data: jsonPoint
                    });
                    this.sourceArr.push('points')
                    this.map.addLayer({
                        id: 'points',
                        type: 'circle',
                        source: 'points',
                        paint: {
                            'circle-color': '#ffffff',
                            'circle-radius': 3,
                            'circle-stroke-width': 2,
                            'circle-stroke-color': "#ff0000"
                        }
                    });
                    this.layerIds.push('points');
                }
                let points = [];
                let starCoord = [];
                this.map.on('click', e => {
                    if (isDraw) {
                        starCoord = [];
                        starCoord.push(e.lngLat.lng);
                        starCoord.push(e.lngLat.lat);
                        points.push(starCoord);
                        console.log(e)
                        if (true) {
                            this.map.getCanvas().style.cursor = 'grab';
                            isDraw = false;
                            let endCoor = [e.lngLat.lng, e.lngLat.lat];
                            jsonPoint.features.push({
                                type: 'Feature',
                                geometry: {
                                    type: 'Point',
                                    coordinates: endCoor
                                }
                            });
                            this.map.getSource('points').setData(jsonPoint);
                        }
                    }
                });

            },
            initLineTool() {
                console.log('initLine');
                this.map.getCanvas().style.cursor = 'crosshair';
                this.clearMap(this.markerArr, this.layerIds, this.sourceArr);
                let isMeasure = true;
                this.map.doubleClickZoom.disable();//禁止双击缩放
                let jsonPoint = {
                    'type': 'FeatureCollection',
                    'features': []
                }
                let jsonLine = {
                    'type': 'FeatureCollection',
                    'features': []
                }
                let markers = [];
                let source = this.map.getSource('points');
                let lineMoveSource = this.map.getSource('line-move');
                let lineSource = this.map.getSource('line');
                if (source) {
                    this.map.getSource('points').setData(jsonPoint);
                    if (lineMoveSource) {
                        this.map.getSource('line-move').setData(lineMoveSource);
                    }
                    if (lineSource) {
                        this.map.getSource('line').setData(jsonLine);
                    }
                } else {
                    this.map.addSource('points', {
                        type: 'geojson',
                        data: jsonPoint
                    });
                    this.map.addSource('line', {
                        type: 'geojson',
                        data: jsonLine
                    });
                    this.map.addSource('line-move', {
                        type: 'geojson',
                        data: jsonLine
                    });
                    this.sourceArr.push(...['points', 'line', 'line-move'])
                    // debugger
                    this.map.addLayer({
                        id: 'line-move',
                        type: 'line',
                        source: 'line-move',
                        paint: {
                            'line-color': '#ff0000',
                            'line-width': 2,
                            'line-opacity': 0.65
                        }
                    });
                    this.map.addLayer({
                        id: 'line',
                        type: 'line',
                        source: 'line',
                        paint: {
                            'line-color': '#ff0000',
                            'line-width': 2,
                            'line-opacity': 0.65
                        }
                    });
                    this.map.addLayer({
                        id: 'points',
                        type: 'circle',
                        source: 'points',
                        paint: {
                            'circle-color': '#ffffff',
                            'circle-radius': 3,
                            'circle-stroke-width': 2,
                            'circle-stroke-color': "#ff0000"
                        }
                    });
                    this.layerIds.push(...['points', 'line', 'line-move'])

                }
                let that = this;

                function addPoint(coords) {
                    // debugger
                    if (jsonPoint.features.length > 0) {
                        let prev = jsonPoint.features[jsonPoint.features.length - 1];
                        jsonLine.features.push({
                            type: 'Feature',
                            geometry: {
                                type: 'LineString',
                                coordinates: [prev.geometry.coordinates, coords]
                            }
                        });
                        that.map.getSource('line').setData(jsonLine);
                    }
                    jsonPoint.features.push({
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: coords
                        }
                    });
                    that.map.getSource('points').setData(jsonPoint);
                }

                this.map.on('click', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        addPoint(coords);
                        this.coordsStr += e.lngLat.lng + ',' + e.lngLat.lat + ",";
                    }
                });
                this.map.on('mousemove', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        this.coordsStr += e.lngLat.lng + ',' + e.lngLat.lat + ",";
                        if (jsonPoint.features.length > 0) {
                            let prev = jsonPoint.features[jsonPoint.features.length - 1];
                            let json = {
                                type: 'Feature',
                                geometry: {
                                    type: 'LineString',
                                    coordinates: [prev.geometry.coordinates, coords]
                                }
                            };
                            this.map.getSource('line-move').setData(json);
                        }
                    }
                });
                this.map.on('dblclick', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        addPoint(coords);
                        isMeasure = false;
                        this.map.getCanvas().style.cursor = 'grab';
                        jsonPoint.features = [];
                        jsonLine.features = [];
                    }
                });
            },
            initPoygonTool() {
                console.log('initPoly')
                this.map.getCanvas().style.cursor = 'crosshair';
                this.clearMap(this.markerArr, this.layerIds, this.sourceArr);
                let isMeasure = true;
                this.map.doubleClickZoom.disable();//禁止双击缩放
                let jsonPoint = {
                    'type': 'FeatureCollection',
                    'features': []
                }
                let jsonLine = {
                    'type': 'FeatureCollection',
                    'features': []
                }
                let points = [];
                let source = this.map.getSource('points-area');
                if (source) {
                    this.map.getSource('points-area').setData(jsonPoint);
                    this.map.getSource('line-area').setData(jsonLine);
                } else {
                    this.map.addSource('points-area', {
                        type: 'geojson',
                        data: jsonPoint
                    });
                    this.map.addSource('line-area', {
                        type: 'geojson',
                        data: jsonLine
                    });
                    this.sourceArr.push(...['points-area', 'line-area']);
                    this.map.addLayer({
                        id: 'line-area',
                        type: 'fill',
                        source: 'line-area',
                        paint: {
                            'fill-color': '#ff0000',
                            'fill-opacity': 0.65
                        }
                    });
                    this.map.addLayer({
                        id: 'line-area-stroke',
                        type: 'line',
                        source: 'line-area',
                        paint: {
                            'line-color': '#ff0000',
                            'line-width': 2,
                            'line-opacity': 0.65
                        }
                    });
                    this.map.addLayer({
                        id: 'points-area',
                        type: 'circle',
                        source: 'points-area',
                        paint: {
                            'circle-color': '#ffffff',
                            'circle-radius': 3,
                            'circle-stroke-width': 2,
                            'circle-stroke-color': "#ff0000"
                        }
                    });
                    this.layerIds.push(...['line-area', 'line-area-stroke', 'points-area']);
                }
                let that = this;

                function addPoint2(coords) {
                    jsonPoint.features.push({
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: coords
                        }
                    });
                    that.map.getSource('points-area').setData(jsonPoint);
                }

                this.map.on('click', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        points.push(coords);
                        addPoint2(coords)
                    }
                });
                this.map.on('dblclick', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        points.push(coords);
                        isMeasure = false;
                        this.map.getCanvas().style.cursor = 'grab';
                    }
                });
                this.map.on('mousemove', e => {
                    if (isMeasure) {
                        let coords = [e.lngLat.lng, e.lngLat.lat];
                        let len = jsonPoint.features.length;
                        if (len != 0 && len != 1) {
                            let pts = points.concat([points[0]]);
                            let json = {
                                type: 'Feature',
                                geometry: {
                                    type: 'Polygon',
                                    coordinates: [pts]
                                }
                            }
                            this.map.getSource('line-area').setData(json);
                        }
                    }
                });

            },
            postNewLayer() {
                this.coordsStr = this.coordsStr.slice(0, this.coordsStr.length - 1);//去掉尾部字符
                // let data = {
                //     "bdid": sessionStorage.getItem('bdid'),
                //     "lx": this.selLayerTypeNum,
                //     "mc": this.drawForm.layerName,
                //     "ms": "",
                //     "sj": "",
                //     "smid": 0,
                //     "smname": this.selLayerName[1],
                //     "wz": this.coordsStr,
                //     "zt": 2,//状态：0 已更新 1 已忽略 2 未处理
                //     "ztmc": "",
                //     "bs": (this.drawForm.flag == "敌方") ? 0 : 1,
                // }

                let data = {
                    "bdid": "",
                    "lx": this.selLayerTypeNum,
                    "mc": this.drawForm.layerName,
                    "ms": "",
                    "sj": "",
                    "smid": 0,
                    "smname": this.selLayerName[1],
                    "wz": this.coordsStr,
                    "zt": 2,//状态：0 已更新 1 已忽略 2 未处理
                    "ztmc": "",
                    "bs": (this.drawForm.flag == "敌方") ? 0 : 1,
                }
                // addGaofenItem(data).then(res => {
                //     console.log(res)
                //
                // }).catch(e => {
                //     console.log(e)
                // })

                //向后台发送请求
                let ifSuccess = $App.addGaofenItem(JSON.stringify(data));
                if(ifSuccess == "0"){
                    this.$message({
                        type: 'success',
                        message: '创建图层成功'
                    });
                }else {
                    this.$message({
                        type: 'warning',
                        message: '创建图层失败'
                    });
                }

                this.closeDrawPanel();
            },

            postNewTask() {
                //添加起点
                let tmpObj = {
                    longitude: this.startPoint._lngLat.lng,
                    latitude: this.startPoint._lngLat.lat,
                    altitude: ''
                }
                this.taskPointArr.push(tmpObj);
                //添加途径点
                this.tujingPointArr.forEach(item => {
                    let tmpObj = {
                        longitude: item._lngLat.lng,
                        latitude: item._lngLat.lat,
                        altitude: ''
                    }
                    this.taskPointArr.push(tmpObj);
                })
                //添加终点
                let tmpObj2 = {
                    longitude: this.endPoint._lngLat.lng,
                    latitude: this.endPoint._lngLat.lat,
                    altitude: ''
                }
                this.taskPointArr.push(tmpObj2);
                console.log(JSON.stringify(this.taskPointArr));
                // let data = {
                //     "fsbdid": this.$systemMes.loginId,
                //     "fsztmc": this.$systemMes.loginName,
                //     "jsbdid": this.$systemMes.receiveId,
                //     "jsztmc": this.$systemMes.receiveName,
                //     "ljlx": this.routeForm.resource,
                //     "ljtjd": JSON.stringify(this.taskPointArr),//[{'longitude:'',latitude:'',altitude:''},...]
                //     "mc": this.routeForm.name,
                //     "zt": 0,//0 未执行 1 执行中 2 已完成
                // }

                let data = {
                    "ljlx": this.routeForm.resource,
                    "ljtjd": JSON.stringify(this.taskPointArr),//[{'longitude:'',latitude:'',altitude:''},...]
                    "mc": this.routeForm.name,
                    "zt": 0,//0 未执行 1 执行中 2 已完成
                }

                //不需要新增任务
                // $App.addNewTask(JSON.stringify(data));

                // addNewTask(data).then(res => {
                //     console.log(res);
                //     let taskXH = res.data;//新增高分/任务接口 ---成功返回ID
                //     // 发送任务短报文到聊天
                //     sendMessage({
                //         "fsbdid": this.$systemMes.loginId,
                //         "fsztmc": this.routeForm.name,
                //         "jsbdid": this.$systemMes.receiveId,//空标识平台
                //         "jsztmc": this.$systemMes.receiveName,
                //         "nr": taskXH,
                //         "nrlx": 2,//0 短报文信息 1 高分数据 2 任务数据（导航）
                //
                //     }).then(res => {
                //         this.$message({
                //             type: 'success',
                //             message: '新增任务成功'
                //         });
                //     }).catch(e => {
                //         console.log("发送失败")
                //     });
                //
                //
                // }).catch(e => {
                //     console.log(e)
                // });



            },//新增任务
            async addLine(nodeArr) {
                let tmpArr = JSON.parse(JSON.stringify(this.pathNode))
                let navMesObj = {
                    lineFeature: null,
                    pointFeature: null
                }
                let data = {
                    "isUsingRoad": 1,
                    "isReturnGuide": 1,
                    "nodes": tmpArr
                };

                let data2 = {
                    isUsingRoad: this.routeForm.isUsingRoad, // int 路径规划方式 0:野外、 1:路网
                    isUsingFoot: null, //  int路径规划时候是否利用足迹导航进行辅助， 0:不使用、 1:使用
                    nodes: this.pathNode, //路径规划途经点
                    barrierPoints: null,
                    weightType: this.mode, //int, //权重类型，路网规划时候使用，0为距离最短，1为在野外路径规划时耗费最小、在路网路径规划时时间最短

                    //路网规划使用
                    equHigh: this.routeForm.equHigh, //装备高度 仅在路网路径规划时 结合道路限高使用
                    equWeigh: this.routeForm.equWeigh, // double装备重量，路网规划时候，结合道路限重使用
                    equWidth: this.routeForm.equWidth, // double 装备宽度，路网路径规划时，结合道路限宽使用
                    isReturnGuide: 1, //路径规划时是否需要导航信息 0 为不需要 1为需要

                    //无路网规划
                    equLx: this.routeForm.modesNoRoad[2].equLx, //装备类型，装备类型 仅在野外路径规划中有用，0为无类型；1为普通类（不可过森林）；2为越野类（可过森林)
                    equType: this.routeForm.modesNoRoad[1].equType, // int, 装备类型，野外路径规划使用， 0：无类型、 1:坦克类（不可过水）、2:两栖类（可过水）
                    maxSlopDegree: this.routeForm.slopeValue//最大上坡角度 仅在野外路径规划使用，0-90度
                }
                // console.log(data);

                let res = await axios.post('http://192.168.0.121:5080/bdgis/route', data2);
                let result = res.data;
                console.log(result);
                if (result.data != null) {
                    this.imitateGuides = result.data.guides;
                    this.imitatePointList = result.data.points;
                    console.log(this.imitateGuides);
                    console.log(this.imitatePointList);
                    let points = result.data.points;
                    let feature = {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            type: 'LineString',
                            coordinates: []//coordinates
                        }
                    };
                    let pointsSourceData = {
                        type: 'FeatureCollection',
                        features: []
                    }
                    for (let i = 0; i < points.length; i++) {
                        let pointFeature = {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: []//coordinates
                            }
                        };
                        let tmpLat = points[i].latitude;
                        let tmpLon = points[i].longitude;
                        let tmpPoint = [tmpLon, tmpLat];
                        //线的geojson
                        feature.geometry.coordinates.push(tmpPoint);
                        //多个点的geojson
                        if (i > 1) {
                            pointFeature.geometry.coordinates = tmpPoint;
                            pointsSourceData.features.push(pointFeature);
                        }
                    }
                    navMesObj.lineFeature = feature;
                    navMesObj.pointFeature = pointsSourceData;

                    this.map.addSource('lineSource', {
                        'type': 'geojson',
                        'data': feature
                    });
                    this.map.addLayer({
                        id: 'route1',
                        type: 'line',
                        source: 'lineSource',
                        layout: {},
                        paint: {
                            'line-color': '#31881e',
                            'line-width': 2
                        }
                    });
                    this.layerIds.push('route1');

                    //添加起点
                    let dom = document.createElement('img');
                    dom.className = 'marker';
                    dom.style.backgroundImage = `url(./img/start.png)`;
                    this.startPoint = new mapboxgl.Marker({
                        element: dom,
                        offset: [0, -10]
                    }).setLngLat(new mapboxgl.LngLat(this.pathNode[0].longitude, this.pathNode[0].latitude)).addTo(this.map);
                    this.markerArr.push(this.startPoint);
                    //添加途径点

                    //添加终点图标
                    let dom1 = document.createElement('img');
                    dom1.className = 'marker';
                    dom1.style.backgroundImage = `url(./img/end.png)`;
                    this.endPoint = new mapboxgl.Marker({
                        element: dom1,
                        offset: [0, -10]
                    }).setLngLat(new mapboxgl.LngLat(this.pathNode[this.pathNode.length - 1].longitude, this.pathNode[this.pathNode.length - 1].latitude)).addTo(this.map);
                    this.markerArr.push(this.endPoint);
                }


            },
            cleanMap() {
                this.clearMap(this.markerArr, this.layerIds, this.sourceArr);
                this.isShowRoutePanel = false;
                this.isShowDrawPanel = false;
                this.isShowNavConPanel = false;

            },
            switchChange() {

                if (this.isopenOrClose) {
                    this.map.setStyle('http://192.168.0.121:5095/bdgis/mapstyle/basic-style.json');
                } else {
                    this.map.setStyle('http://192.168.0.121:5095/bdgis/mapstyle/night-style.json');
                }
            },
            clearMap(markerArr, layerIdArr, sourceArr) {
                //根据id删除所有的图层

                if (layerIdArr.length != 0) {
                    layerIdArr.forEach((item) => {
                        this.map.removeLayer(item);
                    });
                }
                //删除所有的marker
                if (markerArr.length != 0) {
                    markerArr.forEach(item => {
                        item.remove();
                    })
                }
                //删除所有source
                if (sourceArr.length != 0) {
                    sourceArr.forEach(item => {
                        this.map.removeSource(item);
                    });
                }
                this.markerArr = [];
                this.layerIds = [];
                this.sourceArr = [];
            },
            showRoutePanel() {
                /*this.isShowRoutePanel = !this.isShowRoutePanel;
                this.isShowDrawPanel = false;*/
                this.$router.push('/navimap')
            },
            showDrawPanel() {
                this.isShowRoutePanel = false;
                this.isShowDrawPanel = !this.isShowDrawPanel;
            },
            TTSFunction(str) {
                try {
                    $App.speakWord(str);
                } catch (e) {
                    let msg = new window.SpeechSynthesisUtterance(str);
                    window.speechSynthesis.speak(msg);
                }

            }
        },
        watch: {
            drawForm: {
                handler(newVal, oldVal) {
                    this.drawForm.flag = newVal.flag;
                },
                deep: true
            }
        },
        // components:{
        //     'remote-js':{
        //         render(createElement, context) {
        //             console.log("nihahoaoaoaoaoao")
        //             return createElement('script',{attr:{type:'text/javascript',src:this.src3}})
        //         },
        //        props:{
        //            src3:{type:String,require:true}
        //        }
        //     }
        // }

    }
</script>

<style scoped>
    #map {
        width: 100%;
        /*height: 100%;*/
        flex: 1;
        position: relative;
    }

    #top {
        position: absolute;
        width: 100%;
        bottom: 0;
        z-index: 999;
        background: #000;
        opacity: 0.8;
        border-radius: 10px;
        margin-bottom: 10px;
    }

    #Tips {
        position: relative;
        width: 100%;
        /*background: #000;*/
        max-height: 30%;
        overflow: auto;
        padding: 10px;
        color: #fff;
        height: 40px;
        font-size: 14px;
        color: white;
    }

    #timesAdistance {
        position: relative;
        right: 0;
        width: 100%;
        /*background: #000;*/
        max-height: 30%;
        overflow: auto;
        padding: 10px;
        color: #fff;
        font-size: 14px;
        color: white;
    }

    #turnTips {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);

    }

    #turnTips > img {
        width: 80px;
        height: 80px;
    }

    .quit-navi {
        position: absolute;
        right: 10px;
        top: 10px;
        color: white;
        width: 20px;
        height: 20px;
        font-size: 18px;
    }

    #btnControl {
        display: none;
        position: absolute;
        top: 30%;
        left: 0;
        z-index: 99999;
    }

    #btnControl > div {
        display: flex;
        flex-direction: column;
    }

    #btnControl button {
        width: 100px;
    }


    .controldiv {
        width: 45px;
        height: 100px;
        position: absolute;
        right: 11px;
        top: 65px;

        border-radius: 10px;
        z-index: 999;
    }

    .controldiv > div {
        width: 45px;
        height: 45px;
        /*border: 1px solid red;*/
        border-radius: 10px;
        background: white;
        margin-top: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

    .controldiv > div:nth-child(3) {
        padding: 10px;
    }

    .controldiv img {
        height: 100%;
        width: 100%;
    }

    .controldiv .highlight {
        color: #0d98ed;
    }

    .routePanel {
        width: 100%;
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
        /*border: 1px solid red;*/
        border-radius: 10px;
        z-index: 999;
        background-color: rgba(255, 255, 255, 1);
        padding: 10px;
        /*margin-bottom: 20px;*/
    }

    /deep/ .el-collapse-item__header {
        height: 30px;
        color: #c0c4cc;
    }

    /deep/ .el-form-item {
        margin-bottom: 3px !important;
    }

    /deep/ .el-input__inner {
        background-color: #eee;
        border-radius: 5px;
    }

    /deep/ .item-btn > div {
        display: flex !important;
        flex-direction: row !important;
        justify-content: space-between !important;
    }

    /deep/ .el-collapse-item__header {
        background-color: #eee;
        padding-left: 15px;
        border-radius: 5px;
    }

    /deep/ .el-collapse-item__content > div {
        margin-top: 3px !important;
    }

    .drawPanel {
        width: 100%;;
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
        /*border: 1px solid red;*/
        border-radius: 10px;
        z-index: 999;
        background-color: rgba(255, 255, 255, 1);
        padding: 10px;
    }

    .draw_box {

    }

    .draw_box > div {
        flex: 1;
        padding: 5px;
        border: 1px solid red;
    }


</style>
<style>
    .marker {
        width: 32px;
        height: 32px;
    }

    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
        margin-bottom: 1px;
    }
</style>